<?php

//路由分发
class Controller {

    public $view;
    protected $post;
    protected $get;
    protected $request;
    protected $session;
    protected $db;
    protected $cfg;

    public function __construct() {
        $this->view = new View();
        $this->post = $_POST;
        $this->get = $_GET;
        $this->request = $_REQUEST;
        $this->session = $_SESSION;
        $this->init();
    }

    protected function init() {
        
    }

    public function assign($var, $val='') {
        $this->view->assign($var, $val);
    }

    public function display($template) {
        $this->view->display($template);
    }

    public function fetch($template) {
        return $this->view->fetch($template);
    }

    public function redirect($url) {
        header('Location: ' . $url);
        eixt;
    }

    public function ajaxReturn($status = 0, $msg = '', $data = array()) {
        // 返回JSON数据格式到客户端 包含状态信息
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode(array('status' => $status, 'msg' => $msg, 'data' => $data)));
    }

    public function isPost() {
        return $_SERVER['REQUEST_METHOD'] == 'POST' ? true : false;
//        
    }

    public function isAjax() {
        return ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')) ? true : false;
    }

    public function post($key = '', $default = null, $func = null) {
        return $this->param('post', $key, $default, $func);
    }

    public function get($key, $default = null, $func = null) {
        return $this->param('get', $key, $default, $func);
    }

    public function request($key, $default = null, $func = null) {
        return $this->param('request', $key, $default, $func);
    }

    protected function param($type = 'post', $key = '', $default = null, $func = null) {
        $data = $this->$type;
        if (empty($key)) {
            if (is_null($default) && !is_null($func)) {
                return array_map($func, $data);
            } else {
                return $data;
            }
        } else {
            if ($func == null) {
                return (isset($data[$key]) && !empty($data[$key])) ? $data[$key] : $default;
            } else {
                return (isset($data[$key]) && !empty($data[$key])) ? $func($data[$key]) : $default;
            }
        }
    }

}
